package com.hq.config;

import com.hq.model.Root;
import com.hq.service.RootService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class RootRealm extends AuthorizingRealm {
    @Autowired
    RootService rootService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override//认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken= (UsernamePasswordToken)token;
        String username = upToken.getUsername ();
        String password = new String(upToken.getPassword());
        String roles = upToken.getHost ();
        //System.out.println ("认证"+roles);
        Root root= rootService.getUsername (username);
        //System.out.println ("root"+root);
        if(root==null){
            throw new UnknownAccountException ("没有此用户");
        }else {
            Root roots = rootService.getUsernameAndPasswordAndRole (username,password,roles);
            if (roots==null){
                throw new AuthenticationException("认证失败。。。");
            }else {
                return new SimpleAuthenticationInfo(token.getPrincipal(),token.getCredentials(),this.getName());
            }
        }
    }
}
